use yew::{platform::spawn_local, prelude::*};
use yew_router::prelude::*;

use crate::{
  api::rustaceans::api_rustaceans, contexts::CurrentUserContext,
  hooks::use_rustaceans, Route,
};

#[derive(Properties, PartialEq)]
pub struct Props {
  pub token: AttrValue,
}

#[function_component]
pub fn RustaceanList(props: &Props) -> HtmlResult {
  let rustaceans = use_rustaceans(&props.token.clone())?;

  Ok(html! {
    <>
      <p>
        <Link<Route> to={Route::RustaceansAdd}>
          {"+ Add new rustacean"}
        </Link<Route>>
      </p>
      <table>
        <thead>
          <th>{"ID"}</th>
          <th>{"Name"}</th>
          <th>{"Email"}</th>
          <th>{"Crate At"}</th>
          <th>{"Operations"}</th>
        </thead>
        <tbody>
        {
          rustaceans.into_iter().map(|rustacean| {
            html! {
              <tr>
                <td>{rustacean.id}</td>
                <td>{rustacean.name}</td>
                <td>{rustacean.email}</td>
                <td>{rustacean.created_at}</td>
                <td>
                  <Link<Route> to={Route::RustaceansEdit { id: rustacean.id }}>
                    {"edit"}
                  </Link<Route>>
                  {" | "}
                  <Link<Route> to={Route::RustaceansDelete { id: rustacean.id }}>
                    {"delete"}
                  </Link<Route>>
                </td>
              </tr>
            }
          }).collect::<Html>()
        }
        </tbody>
      </table>
    </>
  })
}

#[function_component]
pub fn RustaceanList1() -> Html {
  let current_user_ctx = use_context::<CurrentUserContext>()
    .expect("Current user context is missing");
  // 这里使用 use_state 有bug,会不断的发生状态修改后，不断的重新渲染
  // let rustaceans_handle = use_state(|| vec![]);  使用 use_state_eq 解决
  let rustaceans_handle = use_state_eq(|| vec![]);
  let rustaceans = (*rustaceans_handle).clone();

  match &current_user_ctx.token {
    Some(token) => {
      let cloned_token = token.clone();

      spawn_local(async move {
        let response = api_rustaceans(&cloned_token).await.unwrap();
        rustaceans_handle.set(response);
      });

      html! {
        <>
          <p>
            <Link<Route> to={Route::RustaceansAdd}>
              {"+ Add new rustacean"}
            </Link<Route>>
          </p>
          <table>
            <thead>
              <th>{"ID"}</th>
              <th>{"Name"}</th>
              <th>{"Email"}</th>
              <th>{"Crate At"}</th>
              <th>{"Operations"}</th>
            </thead>
            <tbody>
              {
                rustaceans.into_iter().map(|rustacean| {
                  html! {
                    <tr>
                      <td>{rustacean.id}</td>
                      <td>{rustacean.name}</td>
                      <td>{rustacean.email}</td>
                      <td>{rustacean.created_at}</td>
                      <td>
                        <Link<Route> to={Route::RustaceansEdit { id: rustacean.id }}>
                          {"edit"}
                        </Link<Route>>
                        {" | "}
                        <Link<Route> to={Route::RustaceansDelete { id: rustacean.id }}>
                          {"delete"}
                        </Link<Route>>
                      </td>
                    </tr>
                  }
                }).collect::<Html>()
              }
            </tbody>
          </table>
        </>
      }
    }
    None => html! {
      <Redirect<Route> to={Route::Login}/>
    },
  }
}
